import React, { PureComponent,Fragment } from 'react';
import { Form, Input, InputNumber, Select, DatePicker, Upload, TreeSelect,notification  } from 'antd';
import { connect } from 'dva';
import { worker } from "../../utils/worker"
import "./form.less"
import moment from "moment"
class StructureBase extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            validateRes1: null,
            validateRes2: null,
            fileList: [],
            data: {},
            loading: false,
            expandedKeys: [],
            expandedKeys2: [],
            checkedKeys: [],
            sort: [{ id: '6', name: '盖梁' }, { id: '7', name: '方柱墩身' }, { id: '12', name: "圆柱墩身" }, { id: '11', name: "基础" }],
        }
        this.onConfirm = this.onConfirm.bind(this);
        this.onOk = this.onOk.bind(this)
        this.onSelect = this.onSelect.bind(this)
        this.upload = this.upload.bind(this)
        this.getFormValues = this.getFormValues.bind(this)
        this.updateFormData = this.updateFormData.bind(this)
        this.validate1 = this.validate1.bind(this)
        this.validate2 = this.validate2.bind(this)
        this.onChange1 = this.onChange1.bind(this)
        this.onChange2 = this.onChange2.bind(this)
        this.onCheck = this.onCheck.bind(this)
        this.validate=this.validate.bind(this)
        this.warn=this.warn.bind(this)
    }
    isContained(aa, bb) {
        if (!(aa instanceof Array) || !(bb instanceof Array) || ((aa.length < bb.length))) { return false; }
        var aaStr = aa.toString();
        const len=bb.length
        for (var i = 0; i < len; i++) { if (aaStr.indexOf(bb[i]) < 0) return false; }
        return true;

    }
    getFormValues(check) {
        return new Promise((resolve, reject) => {
            const {form}=this.props;
            if (!check) {
                form.validateFields((error, values) => {
                    if (!error) {
                        resolve(values)
                    } else {
                        reject(error)
                    }
                })
            } else {
                let values = form.getFieldsValue()
                resolve(values)
            }

        })
    }
    onChange1(e) {
        this.setState({
            validateRes1: this.validate1(e)
        })
    }
    onChange2(e) {
        this.setState({
            validateRes2: this.validate2(e)
        })
    }
    warn(message){
        this.st2=setTimeout(()=>{
            clearTimeout(this.st2)
            notification.warn({ message})
        },10)
    }
    validate(e) {
        if(this.st2){
            clearTimeout(this.st2)
        }
        return new Promise((resolve, reject) => {
            let { fileList } = this.state;
            if (e.file.originFileObj.webkitRelativePath.split('/').length > 2) {
                this.warn("此操作上传的文件夹中含有其他文件夹，请移除内部文件夹!")
                reject()
                return;
            }
            if (new RegExp(/\.php|\.exe|\.cmd|\.bat|\.java/).test(e.file.originFileObj.webkitRelativePath)) {
                this.warn("文件非法!")
                reject()
                return;
            }
            fileList.push(e.file)
            this.setState({
                fileList: fileList
            })
            resolve()
        })
    }
    async componentDidMount() {
        const { dictlist, onLoaded,getStructureTree,getCateTree } = this.props;
        if (onLoaded) {
          onLoaded(this);
        }
        let res = await getStructureTree()
        let resc = await worker.loopTreeNode(res, null, true,true)
        if (resc) {
            this.setState({
                expandedKeys: resc.map(item => item.key),
                treeData: resc
            })
        }
        let res2 = await getCateTree()
        let resc2 = await worker.loopTreeNode2(res2, null, true,true)
        if (resc2) {
            this.setState({
                expandedKeys2: resc2.map(item => String(item.key)),
                treeData2: resc2
            })
        }

        this.setState({
            isShowList: dictlist.filter(item => item.dictType == "is_show"),
            isEffectiveList: dictlist.filter(item => item.dictType == "is_effective"),
            definitionFileCategory: dictlist.filter(item => item.dictType == "definition_file_category"),
            dynamicBlock: dictlist.filter(item => item.dictType == "dynamic_block"),
        })

    }

    onConfirm(params = {}) {
        const {form,refStructure}=this.props;
        form.validateFields((error, values) => {
            if (!error) {
                form.resetFields()
                refStructure(values, (structure) => {
                    if (params.onSuccess) {
                        params.onSuccess(structure);
                    }
                }, (error) => {
                    if (params.onError) {
                        params.onError(error);
                    }
                });
            } else {
                if (params.onError) {
                    params.onError(error);
                }
            }
        });
    }
    onSelect(e) {
        const { setFieldsValue } = this.props.form;
        setFieldsValue({
            definitionIds: e
        })
    }
    updateFormData(values) {
        const { data } = this.state;
        values.createTime = moment(values.createTime)
        if(values.definitionTreeId){
            Object.assign(data, values)
            if (values.definitionFiles) {
                this.setState({
                    fileList: values.definitionFiles
                })
            }
            this.setState({
                checkedKeys: data.definitionPartIds,
                data
            })
        }
        
    }
    async upload() {
        this.st = setTimeout(() => {
            if (this.st) {
                clearTimeout(this.st)
            }
            const { fileList, directary } = this.state;
            let formdata = new FormData()
            const files = fileList.map(item => item.originFileObj)
            const len=files.length;
            for (let i = 0; i < len; i++) {
                const item = files[i];
                formdata.append('files', item)
            }
            formdata.append('name', directary)
            this.props.uploadAndAnalyzing(
                formdata,
                (res) => {

                    if (this.props.getFormData) {
                        this.props.getFormData(res)
                    }
                    this.setState({
                        data: res
                    })
                    res.createTime = moment(res.createTime)
                    this.props.form.setFieldsValue(res)
                },
                err => {
                    this.setState({
                        fileList:[]
                    })
                }
            )
        }, 1000)
    }
    onOk(e) {
        console.log(e)
    }
    validate1(value) {
        return value - 0 < 0 || value - 1 > 0 ? {
            validateStatus: 'error',
            errorMsg: "数值0-1之间",
        } : {
                validateStatus: 'success',
                errorMsg: null,
            }

    }
    validate2(value) {
        return value - 0 < 0 || value - 3 > 0 ? {
            validateStatus: 'error',
            errorMsg: "数值0-3之间",
        } : {
                validateStatus: 'success',
                errorMsg: null,
            }

    }
    onCheck(e, a) {
        this.setState({
            checkedKeys: e
        })

    }
    componentWillUnmount() {
        if (this.st) {
            clearTimeout(this.st)
        }
        if (this.st2) {
            clearTimeout(this.st2)
        }
    }
    render() {
        const {
            form = {},
            mode
        } = this.props;
        const _this = this;
        const { getFieldDecorator } = form;
        const { data, checkedKeys, fileList, treeData, treeData2, isShowList, isEffectiveList, definitionFileCategory, dynamicBlock, validateRes1, validateRes2 } = this.state;

        return (
            <Form
                className="strBForm"
                style={{ maxWidth: "1200px", margin: 'auto', border: '1px solid #ececec', padding: '30px 0 0 0', display: 'flex', flexWrap: 'wrap', justifyContent: 'space-evenly' }}
                labelCol={{ span: 7 }}
                wrapperCol={{ span: 17 }}
            ><Form.Item labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }} style={{ width: "90%" }} label='模板路径'>
                    {getFieldDecorator('definitionFiles', {
                        rules: [
                            { required: true, message: '模板路径' }
                        ],
                        initialValue: data ? data.definitionFiles : []
                    })(
                        <Upload
                            accept="*"
                            directory
                            multiple
                            disabled={mode=='overview'}
                            progress={
                                {
                                    strokeColor: {
                                      '0%': '#108ee9',
                                      '100%': '#87d068',
                                    },
                                    strokeWidth: 3,
                                    format: percent => `${parseFloat(percent.toFixed(2))}%`,
                                  }
                            }
                            customRequest={(e) => {

                            }}
                            fileList={fileList}
                            beforeUpload={async e => {
                                if (fileList && fileList.length) {
                                    await this.setState({
                                        fileList: []
                                    })

                                }
                            }}
                            onRemove={file=>{
                                const index = this.state.fileList.indexOf(file);
                                this.state.fileList.splice(index, 1);
                                this.setState({
                                    fileList:[...this.state.fileList]
                                })
                              }}
                            onChange={(e) => {
                                if (_this.st) {
                                    clearTimeout(_this.st)
                                }
                                if (_this.st2) {
                                    clearTimeout(_this.st2)
                                }
                                this.validate(e)
                                if (e.file.originFileObj) {
                                    e.file.status = "done"
                                    this.setState({
                                        directary: e.file.originFileObj.webkitRelativePath.split('/')[0]
                                    })
                                    this.upload()
                                }

                            }}
                        >
                            <div className="upload" style={{ width: '120px', height: '120px', borderRadius: '0.2em', lineHeight: '120px', color: '#888', border: 'dashed 0.5px #d8d8d8', cursor: 'pointer', textAlign: 'center', overflow: 'hidden', marginRight: "10px" }}>
                                <span>上传文件</span>
                            </div>
                        </Upload>
                    )}
                </Form.Item>


                <Form.Item className="half"
                    label='构件名称'>
                    {getFieldDecorator('definitionName', {
                        rules: [
                            { required: true, message: '构件名称' }
                        ],
                        initialValue: data ? data.definitionName : undefined
                    })(
                        <Input />
                    )}
                </Form.Item>
                <Form.Item className="half"
                    label='中文名称'>
                    {getFieldDecorator('definitionNameZh', {
                        rules: [
                            { required: true, message: '中文名称' }
                        ],
                        initialValue: data ? data.definitionNameZh : undefined
                    })(
                        <Input />
                    )}
                </Form.Item>
                <Form.Item className="half" label='构件类别'>
                    {getFieldDecorator('definitionTreeId', {
                        rules: [
                            { required: true, message: '必填' }
                        ],
                        initialValue: data&&data.definitionTreeId ? data.definitionTreeId : undefined
                    })(
                        <TreeSelect
                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                            placeholder="请选择构件"
                            treeData={treeData}
                            treeDefaultExpandAll
                        ></TreeSelect>
                    )}
                </Form.Item>

                <Form.Item className="half" label='块类型'>
                    {getFieldDecorator('dynamicBlock', {
                        rules: [
                            { required: true, message: '块类型' }
                        ],
                        initialValue: data && data.dynamicBlock ? data.dynamicBlock : 84
                    })(
                        <Select placeholder="块类型">
                            {dynamicBlock && dynamicBlock.length > 0 ? dynamicBlock.map((r, i) => (
                                <Select.Option value={r.id} key={r.id}>{r.dictLabel}</Select.Option>
                            )) : ''}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item className="half" label='模板类别'>
                    {getFieldDecorator('definitionFileCategory', {
                        rules: [
                            { required: true, message: '模板类别' }
                        ],
                        initialValue: data && data.definitionFileCategory ? data.definitionFileCategory : 81
                    })(
                        <Select placeholder="模板类别">
                            {definitionFileCategory && definitionFileCategory.length > 0 ? definitionFileCategory.map((r, i) => (
                                <Select.Option value={r.id} key={r.id}>{r.dictLabel}</Select.Option>
                            )) : ''}
                        </Select>
                    )}
                </Form.Item>
                <div className="half">

                </div>
                <Form.Item className="half" label='构件部位'>
                    {getFieldDecorator('definitionPartIds', {
                        rules: [
                            { required: true, message: '必填' }
                        ],
                        initialValue: data ? data.definitionPartIds : undefined
                    })(
                        <TreeSelect
                            multiple
                            onChange={this.onCheck}
                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                            placeholder="请选择构件部位"
                            treeData={treeData2}
                            treeDefaultExpandAll
                        ></TreeSelect>
                    )}
                </Form.Item>
                <div className="half">

                </div>


                    {checkedKeys && checkedKeys.includes('6') ? <Form.Item validateStatus={validateRes1 ? validateRes1.validateStatus : null}
                        help={validateRes1 ? validateRes1.errorMsg : null} className="half" label='盖梁数量'>
                        {getFieldDecorator('cbNum', {
                            rules: [
                                { required: true, message: '盖梁数量' },
                            ],
                            initialValue: mode != 'add' && data.cbNum ? data.cbNum : 1
                        })(
                            <InputNumber onChange={this.onChange1} type="number" />
                        )}
                    </Form.Item> : undefined} 
                    {
                       checkedKeys && checkedKeys.includes('6') ?  <div className="half">

                        </div>:undefined
                    }
                    {checkedKeys && (checkedKeys.includes('7') || checkedKeys.includes('12')) ? <Form.Item validateStatus={validateRes2 ? validateRes2.validateStatus : null}
                        help={validateRes2 ? validateRes2.errorMsg : null} className="half" label='桥墩数量'>
                        {getFieldDecorator('colNum', {
                            rules: [
                                { required: true, message: '桥墩数量' }
                            ],
                            initialValue: mode != 'add' && data.colNum ? data.colNum : 1
                        })(
                            <InputNumber onChange={this.onChange2} type="number" />
                        )}
                    </Form.Item> : undefined}
                    {
                       checkedKeys && (checkedKeys.includes('7') || checkedKeys.includes('12'))  ?  <div className="half">

                        </div>:undefined
                    }
                    {checkedKeys && checkedKeys.includes('11') ? <Form.Item className="half" label='顺桥向桩基个数'>
                        {getFieldDecorator('pileNumL', {
                            rules: [
                                { required: true, message: '顺桥向桩基个数' }
                            ],
                            initialValue: mode != 'add' && data.pileNumL ? data.pileNumL : 0
                        })(
                            <InputNumber type="number" />
                        )}
                    </Form.Item> : undefined}
                    {checkedKeys && checkedKeys.includes('11') ? <Form.Item className="half" label='横桥向桩基个数'>
                        {getFieldDecorator('pileNumW', {
                            rules: [
                                { required: true, message: '横桥向桩基个数' }
                            ],
                            initialValue: mode != 'add' && data.pileNumW ? data.pileNumW : 0
                        })(
                            <InputNumber type="number" />
                        )}
                    </Form.Item> : undefined}
                <div className="ant-row" style={{ width: "100%", display: "flex", justifyContent: "space-between" }}>
                    <Form.Item className="half" label='是否可见'>
                        {getFieldDecorator('isShow', {
                            rules: [
                                { required: true, message: '是否可见' }
                            ],
                            initialValue: data && data.isShow ? data.isShow : 70
                        })(
                            <Select placeholder="是否可见">
                                {isShowList && isShowList.length > 0 ? isShowList.map((r, i) => (
                                    <Select.Option value={r.id} key={r.id}>{r.dictLabel}</Select.Option>
                                )) : ''}
                            </Select>
                        )}
                    </Form.Item>
                    <Form.Item className="half" label='是否生效'>
                        {getFieldDecorator('isEffective', {
                            rules: [
                                { required: true, message: '是否生效' }
                            ],
                            initialValue: data && data.isEffective ? data.isEffective : 72
                        })(
                            <Select placeholder="是否生效">
                                {isEffectiveList && isEffectiveList.length > 0 ? isEffectiveList.map((r, i) => (
                                    <Select.Option value={r.id} key={r.id}>{r.dictLabel}</Select.Option>
                                )) : ''}
                            </Select>
                        )}
                    </Form.Item>
                </div>

                <Form.Item className="half" label='作者'>
                    {getFieldDecorator('author', {
                        rules: [
                            { required: false, message: '作者' }
                        ],
                        initialValue: data ? data.author : undefined
                    })(
                        <Input />
                    )}
                </Form.Item>
                {
                    mode != 'add' ? <Form.Item className="half" label='创建日期' style={mode == 'add' ? { display: 'none' } : {}}>
                        {getFieldDecorator('createTime', {
                            rules: [
                                { required: true, message: '创建日期' }
                            ],
                            initialValue: data ? moment(data.createTime) : null
                        })(
                            <DatePicker disabled showTime placeholder="Select Time" onOk={this.onOk} />
                        )}
                    </Form.Item> : undefined
                }


                <div className="half">

                </div>
                <Form.Item className="half hide" label='路径'>
                        {getFieldDecorator('definitionFileAbsPath', {
                            rules: [
                                { required: true, message: '路径' },
                            ],
                            initialValue:  data.definitionFileAbsPath ? data.definitionFileAbsPath : undefined
                        })(
                            <Input></Input>
                        )}
                    </Form.Item>
                
                {
                    mode != 'add' ? <Form.Item className="hide"
                        label='ID'>
                        {getFieldDecorator('id', {
                            rules: [
                                { required: true, message: '必填' }
                            ],
                            initialValue: data ? data.id : undefined
                        })(
                            <Input />
                        )}
                    </Form.Item> : undefined
                }
                {
                    mode != 'edit' ? <Form.Item className="hide"
                        label='definitionFileName'>
                        {getFieldDecorator('definitionFileName', {
                            rules: [
                                { required: false, message: '必填' }
                            ],
                            initialValue: data ? data.definitionFileName : undefined
                        })(
                            <Input />
                        )}
                    </Form.Item> : undefined
                }
                {
                    mode != 'edit' ? <Form.Item className="hide"
                        label='imgPath'>
                        {getFieldDecorator('imgPath', {
                            rules: [
                                { required: false, message: '必填' }
                            ],
                            initialValue: data ? data.imgPath : undefined
                        })(
                            <Input />
                        )}
                    </Form.Item> : undefined
                }
            </Form>
        );
    }
}

export default connect(
    ({
        dict: { dictlist }
    }) => {
        return { dictlist };
    },
    dispatch => ({
        getStructureTree: (values) => dispatch({
            type: 'structure/getStructureTree',
            payload: values
        }),
        getCateTree: (values) => dispatch({
            type: 'structure/getCateTree',
            payload: values
        }),
        uploadAndAnalyzing: (values, onSuccess, onError) => dispatch({
            type: 'structure/uploadAndAnalyzing',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
    })
)(Form.create('StructureBase', {

})(StructureBase));